package cn.io1;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.Properties;
import java.util.Set;

public class Test09 {
    public static void main(String[] args) {
        // method01();
        // method02();
        method03();
    }

    private static void method03() {
        Properties prop = new Properties();
        try (InputStreamReader reader = new InputStreamReader(new FileInputStream("move/prop2.properties"), StandardCharsets.UTF_8)){
            prop.load(reader);
            System.out.println(prop);
        }catch (Exception e){
            e.printStackTrace();
        }

    }

    /*
        Properties 和 IO 有关的方法

            void load(InputStream inStream)     从输入字节流读取属性列表（键和元素对）
            void load(Reader reader)            从输入字符流读取属性列表（键和元素对）
            void store(OutputStream out, String comments)   将集合的键值对写出到文件(字节流)
            void store(Writer writer, String comments)      将集合的键值对写出到文件(字符流)
     */
    private static void method02() {
        Properties prop = new Properties();
        prop.setProperty("username","admin");
        prop.setProperty("password","123456");
        prop.setProperty("title","吊毛");
        try(FileWriter fos = new FileWriter("move/prop2.properties")){
            prop.store(fos,null);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /*
      Properties作为集合的使用

          Object setProperty (String key, String value) : 类似Map集合的put方法
          String getProperty (String key) : 类似Map集合的get方法
          Set<String> stringPropertyNames() : 类似Map是集合的keySet方法
   */
    private static void method01() {
        Properties prop = new Properties();
        prop.setProperty("username","admin");
        prop.setProperty("password","123456");
        Set<String> keySet = prop.stringPropertyNames();
        try(PrintStream stream = new PrintStream(new FileOutputStream("move/prop.properties"))){
            keySet.forEach(key-> stream.println(key+"="+prop.getProperty(key)));
        }catch (Exception e){
            e.printStackTrace();
        }
        // keySet.forEach(key-> System.out.println(key+":"+prop.getProperty(key)));
    }
}
